package eu.goldenak.ircbot.module;

import eu.goldenak.ircbot.IrcBot;
import eu.goldenak.ircbot.IrcChannel;
import eu.goldenak.ircbot.ConfigManager;
import eu.goldenak.ircbot.ModuleManager;
import java.util.HashMap;

/**
 * This module for the GoldenAK Bot handles joining the channels and identifying
 * with NickServ. This was once part of the core of the bot, but since the
 * introduction of slave bots, that didn't work anymore. Therefore I fixed it
 * properly; with a module, like it should've been from the beginning.
 */
public class Connect extends ModuleBase {
	
	/**
	 * The NickServ password.
	 */
	private String m_sNickServPassword;
	
	/**
	 * The array of all channels we need to join.
	 */
	private IrcChannel [] m_aChannels;
	
	/**
	 * We'll use the constructor to setup and gather the information we'll be
	 * needing when the bot actually connects to the IRC server. This includes
	 * the NickServ pass (if there is one configured), but also the channels
	 * which we are expected to join.
	 */
	public Connect () {
		HashMap<String, String> hmConfig = ConfigManager.getModule ("Main");
		
		m_sNickServPassword = hmConfig.get ("nickservpass");
		
		String [] aChannels = hmConfig.get ("ircchannels").split (",");
		m_aChannels = new IrcChannel [aChannels.length];
		int i = 0;
		
		for (String sChannelInfo : aChannels) {
			m_aChannels [i ++] = new IrcChannel (sChannelInfo.split (" ", 2));
		}
	}
	
	/**
	 * The onConnect() callback will allow us to easily join our channels as
	 * well as identify ourselves to NickServ.
	 */
	public void onConnect (IrcBot pBot) {
		if (m_sNickServPassword != null) {
			pBot.out.privmsg ("NickServ", "IDENTIFY " + m_sNickServPassword);
		}
		
		for (IrcChannel pChannel : m_aChannels) {
			if (pChannel.hasKey ()) {
				pBot.out.join (pChannel.getName (), pChannel.getKey ());
			} else {
				pBot.out.join (pChannel.getName ());
			}
		}
	}
}